package com.chaoxi.picturebackend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chaoxi.picturebackend.api.aliyunai.model.Texttoimage.TextToImageCreateRequest;
import com.chaoxi.picturebackend.api.aliyunai.model.expand.AliYunAiApi;
import com.chaoxi.picturebackend.api.aliyunai.model.expand.CreateOutPaintingTaskRequest;
import com.chaoxi.picturebackend.api.aliyunai.model.expand.CreateOutPaintingTaskResponse;
import com.chaoxi.picturebackend.api.aliyunai.model.expand.CreatePictureOutPaintingTaskRequest;
import com.chaoxi.picturebackend.api.aliyunai.model.Texttoimage.TextToImageApi;
import com.chaoxi.picturebackend.api.aliyunai.model.Texttoimage.TextToImageRequest;
import com.chaoxi.picturebackend.api.aliyunai.model.Texttoimage.TextToImageResponse;
import com.chaoxi.picturebackend.constant.PictureConstant;
import com.chaoxi.picturebackend.exception.BusinessException;
import com.chaoxi.picturebackend.exception.ErrorCode;
import com.chaoxi.picturebackend.exception.ThrowUtils;
import com.chaoxi.picturebackend.manager.OSSManager;
import com.chaoxi.picturebackend.manager.upload.FilePictureUpload;
import com.chaoxi.picturebackend.manager.upload.PictureUploadTemplate;
import com.chaoxi.picturebackend.manager.upload.UrlPictureUpload;
import com.chaoxi.picturebackend.model.dto.file.UploadPictureResult;
import com.chaoxi.picturebackend.model.dto.picture.*;
import com.chaoxi.picturebackend.model.entity.Picture;
import com.chaoxi.picturebackend.model.entity.Space;
import com.chaoxi.picturebackend.model.entity.User;
import com.chaoxi.picturebackend.model.enums.PictureReviewStatusEnum;
import com.chaoxi.picturebackend.model.vo.PictureVO;
import com.chaoxi.picturebackend.model.vo.UserVO;
import com.chaoxi.picturebackend.service.PictureService;
import com.chaoxi.picturebackend.mapper.PictureMapper;
import com.chaoxi.picturebackend.service.SpaceService;
import com.chaoxi.picturebackend.service.UserService;
import com.chaoxi.picturebackend.utils.ColorSimilarUtils;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 朱杰
 * @description 针对表【picture(图片)】的数据库操作Service实现
 * @createDate 2025-09-28 09:15:37
 */
@Service
@Slf4j
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture> implements PictureService {
    @Resource
    private UserService userService;
    @Resource
    private FilePictureUpload filePictureUpload;
    @Resource
    private UrlPictureUpload urlPictureUpload;
    @Resource
    private OSSManager ossManager;
    @Resource
    private SpaceService spaceService;
    @Resource
    private TransactionTemplate transactionTemplate;
    @Resource
    private AliYunAiApi aliYunAiApi;
    @Resource
    private TextToImageApi textToImageApi;

    /**
     * 上传图片
     * @param inputSource 输入源，可以是 MultipartFile 或 String
     * @param pictureUploadRequest 图片上传请求
     * @param loginUser 登录用户
     * @return  图片
     */
    @Override
    public PictureVO uploadPicture(Object inputSource, PictureUploadRequest pictureUploadRequest, User loginUser) {
        // 校验参数
        ThrowUtils.throwIf(pictureUploadRequest == null || inputSource == null || loginUser == null, ErrorCode.PARAMS_ERROR);
        // 校验空间是否存在
        Long spaceId = pictureUploadRequest.getSpaceId();
        if (spaceId != null){
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR);
            // 必须空间创建人才能上传
            ThrowUtils.throwIf(!ObjUtil.equals(space.getUserId(), loginUser.getId()), ErrorCode.NO_AUTH_ERROR, "无空间权限");
            // 校验额度
            if (space.getTotalCount() >= space.getMaxCount()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间可上传数量不足");
            }
            if (space.getTotalSize() >= space.getMaxSize()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间大小不足");
            }
        }
        // 判断是新增还是更新
        Long pictureId = null;
        if(pictureUploadRequest.getId() != null){
            pictureId = pictureUploadRequest.getId();
        }
        // 如果是更新，判断图片是否存在
        if(pictureId != null){
            Picture oldPicture = this.getById(pictureId);
            ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
            // 仅本人和管理员才可修改
            if(!ObjUtil.equals(oldPicture.getUserId(), loginUser.getId()) && !userService.isAdmin(loginUser)){
                ThrowUtils.throwIf(!userService.isAdmin(loginUser), ErrorCode.NO_AUTH_ERROR, "无管理员权限");
            }
            // 校验空间是否一致
            // 没传 spaceId，则复用原有图片的 spaceId
            if (spaceId == null) {
                if (oldPicture.getSpaceId() != null) {
                    spaceId = oldPicture.getSpaceId();
                }
            } else {
                // 传了 spaceId，必须和原有图片一致
                if (ObjUtil.notEqual(spaceId, oldPicture.getSpaceId())) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间 id 不一致");
                }
            }

        }
        // 上传图片，得到图片信息
        // 按照用户 id 划分目录 => 按照空间划分目录
        String uploadPathPrefix;
        if (spaceId == null) {
            uploadPathPrefix = String.format("public/%s",loginUser.getId());
        } else {
            uploadPathPrefix = String.format("space/%s", spaceId);
        }
        // 根据 inputSource 类型区分上传方式
        PictureUploadTemplate pictureUploadTemplate = filePictureUpload;
        if (inputSource instanceof String) {
            pictureUploadTemplate = urlPictureUpload;
        }
        log.info("上传图片开始，上传使用类型：{}", pictureUploadTemplate.getClass());
        UploadPictureResult uploadPictureResult = pictureUploadTemplate.uploadPicture(inputSource, uploadPathPrefix);
        // 构造入库的图片信息
        Picture picture = new Picture();
        // 补充设置 spaceId
        picture.setSpaceId(spaceId);
        picture.setOriginUrl(uploadPictureResult.getOriginUrl());
        picture.setCompressUrl(uploadPictureResult.getCompressUrl());
        picture.setThumbnailUrl(uploadPictureResult.getThumbnailUrl());
        String picName = pictureUploadRequest.getName();
        if (picName == null || picName.isEmpty()) {
            picName = uploadPictureResult.getPicName();
        }
        picture.setName(picName);
        // 使用用户输入的简介，如果没有输入则使用默认简介
        picture.setIntroduction(StrUtil.isNotBlank(pictureUploadRequest.getIntroduction())
                ? pictureUploadRequest.getIntroduction()
                : PictureConstant.DEFAULT_PICTURE_INTRODUCTION);
        picture.setPicSize(uploadPictureResult.getPicSize());
        picture.setPicWidth(uploadPictureResult.getPicWidth());
        picture.setPicHeight(uploadPictureResult.getPicHeight());
        picture.setPicScale(uploadPictureResult.getPicScale());
        picture.setPicFormat(uploadPictureResult.getPicFormat());
        picture.setCategory(pictureUploadRequest.getCategory());
        picture.setTags(JSONUtil.toJsonStr(pictureUploadRequest.getTags()));
        picture.setUserId(loginUser.getId());
        picture.setCreateTime(new Date());
        picture.setPicColor(uploadPictureResult.getPicColor());
        // 补充审核参数
        fillReviewParams(picture, loginUser);
        //操作数据库
        if(pictureId != null){
            // 如果id不为空,代表是更新
            // 补充id和编辑时间
            picture.setId(pictureId);
            picture.setEditTime(new Date());
        }
        // 开启事务
        Long finalSpaceId = spaceId;
        transactionTemplate.execute(status -> {
            boolean result = this.saveOrUpdate(picture);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "图片上传失败");
            if (finalSpaceId != null) {
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, finalSpaceId)
                        .setSql("totalSize = totalSize + " + picture.getPicSize())
                        .setSql("totalCount = totalCount + 1")
                        .update();
                ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "额度更新失败");
            }
            return picture;
        });
        return PictureVO.objToVo(picture);
    }

    /**
     * 批量上传图片接口实现
     * <p>
     * 根据搜索关键词从必应图片抓取指定数量的图片，并上传到系统中。
     * 支持设置图片名称前缀，若未设置则使用搜索词作为前缀。
     * 最多支持一次抓取并上传30张图片。
     *
     * @param pictureUploadByBatchRequest 批量上传请求参数对象，包含搜索文本、抓取数量、文件名前缀等信息
     * @param loginUser 当前登录用户信息
     * @return 实际成功上传的图片数量
     */
    @Override
    public int uploadPictureByBatch(PictureUploadByBatchRequest pictureUploadByBatchRequest, User loginUser) {
        String searchText = pictureUploadByBatchRequest.getSearchText();
        // 格式化数量
        Integer count = pictureUploadByBatchRequest.getCount();
        // 获取名称前缀并进行加工处理
        String namePrefix = pictureUploadByBatchRequest.getNamePrefix();
        // 获取图片分类
        String category = pictureUploadByBatchRequest.getCategory();
        // 获取标签
        List<String> tags = pictureUploadByBatchRequest.getTags();

        if (StrUtil.isBlank(namePrefix)) {
            namePrefix = searchText;
        } else {
            // 对前缀进行加工处理
            namePrefix = processNamePrefix(namePrefix);
            // 如果处理后为空，则使用搜索词
            if (StrUtil.isBlank(namePrefix)) {
                namePrefix = searchText;
            }
        }
        // 参数校验：最大允许上传30张图片
        ThrowUtils.throwIf(count > 30, ErrorCode.PARAMS_ERROR, "最多获取 30 条");

        // 构造必应图片异步加载URL
        String fetchUrl = String.format("https://cn.bing.com/images/async?q=%s&mmasync=1", searchText);
        // 获取页面
        Document document;
        try {
            document = Jsoup.connect(fetchUrl).get();
        } catch (IOException e) {
            log.error("获取页面失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取页面失败");
        }
        // 查找包含图片列表的容器元素
        Element div = document.getElementsByClass("dgControl").first();
        if (ObjUtil.isNull(div)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取元素失败");
        }
        // 提取所有缩略图元素
        Elements imgElementList = div.select("img.mimg");
        int uploadCount = 0;
        log.info("开始遍历图片元素，总共找到 {} 个图片元素", imgElementList.size());
        // 遍历图片元素进行下载与上传处理
        for (Element imgElement : imgElementList) {
            // url
            String fileUrl = imgElement.attr("src");
            log.info("开始处理图片元素：{}", fileUrl);
            // 图片描述文字
//            String altText = imgElement.attr("alt");
            // 图片标题
//            String title = imgElement.attr("title");
            if (StrUtil.isBlank(fileUrl)) {
                continue;
            }
            // 去除URL中的查询参数以避免转义问题
            int questionMarkIndex = fileUrl.indexOf("?");
            if (questionMarkIndex > -1) {
                fileUrl = fileUrl.substring(0, questionMarkIndex);
                log.info("去除URL中的查询参数：{}", fileUrl);
            }
            // 构建单个图片上传请求
            PictureUploadRequest pictureUploadRequest = new PictureUploadRequest();
            pictureUploadRequest.setCategory(category);
            pictureUploadRequest.setTags(tags);
            if (StrUtil.isNotBlank(namePrefix)) {
                // 取后6位
                String timestamp = String.valueOf(System.currentTimeMillis() % 1000000);
                pictureUploadRequest.setPicName(namePrefix + "_" + timestamp + "_" + (uploadCount + 1));
                pictureUploadRequest.setName(namePrefix + "_" + timestamp + "_" + (uploadCount + 1));
            }
            try {
                // 调用上传方法执行实际上传逻辑
                PictureVO pictureVO = this.uploadPicture(fileUrl, pictureUploadRequest, loginUser);
                uploadCount++;
            } catch (Exception e) {
                log.error("图片上传失败", e);
                continue;
            }
            // 达到目标上传数后提前结束循环
            if (uploadCount >= count) {
                break;
            }
        }
        return uploadCount;
    }

    @Override
    public CreateOutPaintingTaskResponse createPictureOutPaintingTask(CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest, User loginUser) {
        // 获取图片信息
        Long pictureId = createPictureOutPaintingTaskRequest.getPictureId();
        // optional的抛出异常写法
        Picture picture = Optional.ofNullable(this.getById(pictureId))
                .orElseThrow(() -> new BusinessException(ErrorCode.NOT_FOUND_ERROR));
        // 权限校验
        checkPictureAuth(loginUser, picture);
        // 构造请求参数
        CreateOutPaintingTaskRequest taskRequest = new CreateOutPaintingTaskRequest();
        CreateOutPaintingTaskRequest.Input input = new CreateOutPaintingTaskRequest.Input();
        input.setImageUrl(picture.getOriginUrl());
        taskRequest.setInput(input);
        BeanUtil.copyProperties(createPictureOutPaintingTaskRequest, taskRequest);
        // 创建任务
        return aliYunAiApi.createOutPaintingTask(taskRequest);
    }


    /**
     * 根据 PictureQueryRequest 对象构建用于查询 Picture 实体的 QueryWrapper 条件构造器。
     * <p>
     * 支持根据多个字段进行等值、模糊匹配和范围查询，并支持按指定字段排序。
     * 同时处理了标签（tags）作为 JSON 字符串数组的模糊匹配逻辑。
     *
     * @param pictureQueryRequest 查询请求封装对象，包含各类查询条件。若为 null，则返回空的查询条件。
     * @return 构造好的 QueryWrapper<Picture> 查询条件构造器实例
     */
    @Override
    public QueryWrapper<Picture> getQueryWrapper(PictureQueryRequest pictureQueryRequest) {
        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
        if (pictureQueryRequest == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = pictureQueryRequest.getId();
        String name = pictureQueryRequest.getName();
        String introduction = pictureQueryRequest.getIntroduction();
        String category = pictureQueryRequest.getCategory();
        List<String> tags = pictureQueryRequest.getTags();
        Long picSize = pictureQueryRequest.getPicSize();
        Integer picWidth = pictureQueryRequest.getPicWidth();
        Integer picHeight = pictureQueryRequest.getPicHeight();
        Double picScale = pictureQueryRequest.getPicScale();
        String picFormat = pictureQueryRequest.getPicFormat();
        String searchText = pictureQueryRequest.getSearchText();
        Long userId = pictureQueryRequest.getUserId();
        String sortField = pictureQueryRequest.getSortField();
        String sortOrder = pictureQueryRequest.getSortOrder();
        Integer reviewStatus = pictureQueryRequest.getReviewStatus();
        String reviewMessage = pictureQueryRequest.getReviewMessage();
        Long reviewerId = pictureQueryRequest.getReviewerId();
        Long spaceId = pictureQueryRequest.getSpaceId();
        boolean nullSpaceId = pictureQueryRequest.isNullSpaceId();
        Date startEditTime = pictureQueryRequest.getStartEditTime();
        Date endEditTime = pictureQueryRequest.getEndEditTime();

        // 多字段模糊搜索：name 或 introduction 包含 searchText
        if (StrUtil.isNotBlank(searchText)) {
            // 需要拼接查询条件
            queryWrapper.and(qw -> qw.like("name", searchText)
                    .or()
                    .like("introduction", searchText)
                    .or()
                    .like("category", searchText)
                    .or()
                    .like("tags", "\"" + searchText + "\"")
            );
        }

        // 等值与模糊匹配条件设置
        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        queryWrapper.like(StrUtil.isNotBlank(introduction), "introduction", introduction);
        queryWrapper.like(StrUtil.isNotBlank(picFormat), "picFormat", picFormat);
        queryWrapper.eq(StrUtil.isNotBlank(category), "category", category);
        queryWrapper.eq(ObjUtil.isNotEmpty(picWidth), "picWidth", picWidth);
        queryWrapper.eq(ObjUtil.isNotEmpty(picHeight), "picHeight", picHeight);
        queryWrapper.eq(ObjUtil.isNotEmpty(picSize), "picSize", picSize);
        queryWrapper.eq(ObjUtil.isNotEmpty(picScale), "picScale", picScale);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewStatus), "reviewStatus", reviewStatus);
        queryWrapper.like(StrUtil.isNotBlank(reviewMessage), "reviewMessage", reviewMessage);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewerId), "reviewerId", reviewerId);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceId), "spaceId", spaceId);
        queryWrapper.isNull(nullSpaceId, "spaceId");
        // 时间范围搜索
        // >= startEditTime
        queryWrapper.ge(startEditTime != null, "editTime", startEditTime);
        // < endEditTime
        queryWrapper.le(endEditTime != null, "editTime", endEditTime);

        // 标签字段模糊匹配（JSON 数组形式）
        if (CollUtil.isNotEmpty(tags)) {
            for (String tag : tags) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        // 排序设置
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

    /**
     * 获取图片的封装视图对象
     *
     * @param picture 图片实体对象
     * @param request HTTP请求对象
     * @return 图片的视图封装对象
     */
    @Override
    public PictureVO getPictureVO(Picture picture, HttpServletRequest request) {
        // 对象转封装类
        PictureVO pictureVO = PictureVO.objToVo(picture);
        // 关联查询用户信息
        Long userId = picture.getUserId();
        if (userId != null && userId > 0) {
            User user = userService.getById(userId);
            UserVO userVO = userService.getUserVO(user);
            pictureVO.setUser(userVO);
        }
        return pictureVO;
    }

    /**
     * 分页获取图片封装
     *
     * @param picturePage 图片分页数据
     * @param request     HTTP请求对象
     * @return 封装后的图片分页数据
     */
    @Override
    public Page<PictureVO> getPictureVOPage(Page<Picture> picturePage, HttpServletRequest request) {
        List<Picture> pictureList = picturePage.getRecords();
        Page<PictureVO> pictureVOPage = new Page<>(picturePage.getCurrent(), picturePage.getSize(), picturePage.getTotal());
        if (CollUtil.isEmpty(pictureList)) {
            return pictureVOPage;
        }
        // 对象列表 => 封装对象列表
        List<PictureVO> pictureVOList = pictureList.stream().map(PictureVO::objToVo).collect(Collectors.toList());
        // 1. 关联查询用户信息
        Set<Long> userIdSet = pictureList.stream().map(Picture::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 2. 填充信息
        pictureVOList.forEach(pictureVO -> {
            Long userId = pictureVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            pictureVO.setUser(userService.getUserVO(user));
        });
        pictureVOPage.setRecords(pictureVOList);
        return pictureVOPage;
    }

    /**
     * 校验图片数据是否合法
     *
     * @param picture 待校验的图片对象
     */
    @Override
    public void validPicture(Picture picture) {
        ThrowUtils.throwIf(picture == null, ErrorCode.PARAMS_ERROR);
        // 从对象中取值
        Long id = picture.getId();
        String originUrl = picture.getOriginUrl();
        String introduction = picture.getIntroduction();
        // 修改数据时，id 不能为空，有参数则校验
        ThrowUtils.throwIf(ObjUtil.isNull(id), ErrorCode.PARAMS_ERROR, "id 不能为空");
        if (StrUtil.isNotBlank(originUrl)) {
            ThrowUtils.throwIf(originUrl.length() > 1024, ErrorCode.PARAMS_ERROR, "url 过长");
        }
        if (StrUtil.isNotBlank(introduction)) {
            ThrowUtils.throwIf(introduction.length() > 800, ErrorCode.PARAMS_ERROR, "简介过长");
        }
    }
    /**
     * 下载图片
     *
     * @param pictureId 图片id
     * @return 图片下载地址
     */
    @Override
    public String downloadPicture(String pictureId) {
        Picture picture = this.getById(pictureId);
        if (picture == null){
            return null;
        }
        return picture.getOriginUrl();
    }

    /**
     * 图片审核
     * @param pictureReviewRequest 图片审核请求参数
     */
    @Override
    public void doPictureReview(PictureReviewRequest pictureReviewRequest,User loginUser) {
        // 1.校验参数
        ThrowUtils.throwIf(pictureReviewRequest == null, ErrorCode.PARAMS_ERROR);
        Long id = pictureReviewRequest.getId();
        Integer reviewStatus = pictureReviewRequest.getReviewStatus();
        PictureReviewStatusEnum pictureReviewStatusEnum = PictureReviewStatusEnum.getEnumByValue(reviewStatus);
        String reviewMessage = pictureReviewRequest.getReviewMessage();
        if(StringUtils.isBlank(reviewMessage)){
            reviewMessage = "管理员自动过审";
        }
        ThrowUtils.throwIf(id == null || reviewStatus == null || PictureReviewStatusEnum.REVIEWING.equals(pictureReviewStatusEnum), ErrorCode.PARAMS_ERROR);

        // 2.判断图片是否存在
        Picture oldPicture = this.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 3.校验审核状态是否重复
        if(oldPicture.getReviewStatus().equals(reviewStatus)){
            ThrowUtils.throwIf(true, ErrorCode.OPERATION_ERROR, "请勿重复审核");
        }
        // 4.操作数据库
        Picture updatePicture = new Picture();
        BeanUtil.copyProperties(pictureReviewRequest, updatePicture);
        updatePicture.setReviewerId(loginUser.getId());
        updatePicture.setReviewTime(new Date());
        updatePicture.setReviewMessage(reviewMessage);
        boolean result = this.updateById(updatePicture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
    }

    @Override
    public void fillReviewParams(Picture picture, User loginUser) {
        if (userService.isAdmin(loginUser)) {
            // 管理员自动过审
            picture.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            picture.setReviewerId(loginUser.getId());
            picture.setReviewMessage("管理员自动过审");
            picture.setReviewTime(new Date());
        } else {
            // 非管理员，创建或编辑都要改为待审核
            picture.setReviewStatus(PictureReviewStatusEnum.REVIEWING.getValue());
        }
    }

    @Override
    public void deletePicture(long pictureId, User loginUser) {
        ThrowUtils.throwIf(pictureId <= 0, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        // 判断是否存在
        Picture oldPicture = this.getById(pictureId);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 校验权限
        checkPictureAuth(loginUser, oldPicture);
        // 开启事务
        transactionTemplate.execute(status -> {
            // 操作数据库
            boolean result = this.removeById(pictureId);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
            // 释放额度
            Long spaceId = oldPicture.getSpaceId();
            if (spaceId != null) {
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, spaceId)
                        .setSql("totalSize = totalSize - " + oldPicture.getPicSize())
                        .setSql("totalCount = totalCount - 1")
                        .update();
                ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "额度更新失败");
            }
            return true;
        });
        // 异步清理对象存储的文件
        this.clearPictureFile(oldPicture);
    }

    @Override
    public void editPicture(PictureEditRequest pictureEditRequest, User loginUser) {
        // 在此处将实体类和 DTO 进行转换
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureEditRequest, picture);
        // 注意将 list 转为 string
        picture.setTags(JSONUtil.toJsonStr(pictureEditRequest.getTags()));
        // 设置编辑时间
        picture.setEditTime(new Date());
        // 数据校验
        this.validPicture(picture);
        // 判断是否存在
        long id = pictureEditRequest.getId();
        Picture oldPicture = this.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 校验权限
        checkPictureAuth(loginUser, oldPicture);
        // 补充审核参数
        this.fillReviewParams(picture, loginUser);
        // 操作数据库
        boolean result = this.updateById(picture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editPictureByBatch(PictureEditByBatchRequest pictureEditByBatchRequest, User loginUser) {
        ThrowUtils.throwIf(pictureEditByBatchRequest == null, ErrorCode.PARAMS_ERROR);
        List<Long> pictureIdList = pictureEditByBatchRequest.getPictureIdList();
        Long spaceId = pictureEditByBatchRequest.getSpaceId();
        String category = pictureEditByBatchRequest.getCategory();
        List<String> tags = pictureEditByBatchRequest.getTags();
        // 1. 校验基本参数
        ThrowUtils.throwIf(CollUtil.isEmpty(pictureIdList), ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        // 2. 如果提供了 spaceId，则校验空间权限
        if (spaceId != null) {
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
            if (!loginUser.getId().equals(space.getUserId())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间访问权限");
            }
        }
        // 3. 查询指定图片，根据是否有 spaceId 查询不同范围内的图片
        // 增加 userId 用于后续权限检查
        var query = this.lambdaQuery()
                .select(Picture::getId, Picture::getSpaceId, Picture::getUserId)
                .in(Picture::getId, pictureIdList);
        if (spaceId != null) {
            query.eq(Picture::getSpaceId, spaceId);
        } else {
            // 公共图片
            query.isNull(Picture::getSpaceId);
        }
        List<Picture> pictureList = query.list();
        if (pictureList.isEmpty()) {
            return;
        }
        // 4. 权限校验：确保用户有权编辑这些图片
        for (Picture picture : pictureList) {
            checkPictureAuth(loginUser, picture);
        }
        // 5. 更新分类和标签
        pictureList.forEach(picture -> {
            if (StrUtil.isNotBlank(category)) {
                picture.setCategory(category);
            }
            if (CollUtil.isNotEmpty(tags)) {
                picture.setTags(JSONUtil.toJsonStr(tags));
            }
        });
        // 批量重命名
        String nameRule = pictureEditByBatchRequest.getNameRule();
        fillPictureWithNameRule(pictureList, nameRule);
        // 6. 批量更新
        boolean result = this.updateBatchById(pictureList);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
    }



    @Override
    public void checkPictureAuth(User loginUser, Picture picture) {
        Long spaceId = picture.getSpaceId();
        if (spaceId == null) {
            // 公共图库，仅本人或管理员可操作
            if (!picture.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        } else {
            // 私有空间，仅空间管理员可操作
            if (!picture.getUserId().equals(loginUser.getId())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }
    }

    @Override
    public List<PictureVO> searchPictureByColor(Long spaceId, String picColor, User loginUser) {
        // 1. 校验参数
        ThrowUtils.throwIf(spaceId == null || StrUtil.isBlank(picColor), ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        // 2. 校验空间权限
        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        if (!loginUser.getId().equals(space.getUserId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间访问权限");
        }
        // 3. 查询该空间下所有图片（必须有主色调）
        List<Picture> pictureList = this.lambdaQuery()
                .eq(Picture::getSpaceId, spaceId)
                .isNotNull(Picture::getPicColor)
                .list();
        // 如果没有图片，直接返回空列表
        if (CollUtil.isEmpty(pictureList)) {
            return Collections.emptyList();
        }
        // 将目标颜色转为 Color 对象
        Color targetColor = Color.decode(picColor);
        // 4. 计算相似度并排序
        List<Picture> sortedPictures = pictureList.stream()
                .sorted(Comparator.comparingDouble(picture -> {
                    // 提取图片主色调
                    String hexColor = picture.getPicColor();
                    // 没有主色调的图片放到最后
                    if (StrUtil.isBlank(hexColor)) {
                        return Double.MAX_VALUE;
                    }
                    Color pictureColor = Color.decode(hexColor);
                    // 越大越相似
                    return -ColorSimilarUtils.calculateSimilarity(targetColor, pictureColor);
                }))
                // 取前 12 个
                .limit(12)
                .collect(Collectors.toList());

        // 转换为 PictureVO
        return sortedPictures.stream()
                .map(PictureVO::objToVo)
                .collect(Collectors.toList());
    }


    @Async
    @Override
    public void clearPictureFile(Picture oldPicture) {
        // 判断该图片是否被多条记录使用
        String originUrl = oldPicture.getOriginUrl();
        String compressUrl = oldPicture.getCompressUrl();
        String thumbnailUrl = oldPicture.getThumbnailUrl();

        long count = this.lambdaQuery()
                .eq(Picture::getOriginUrl, originUrl)
                .eq(Picture::getCompressUrl,compressUrl)
                .eq(Picture::getThumbnailUrl,thumbnailUrl)
                .count();
        // 有不止一条记录用到了该图片，不清理
        if (count > 1) {
            return;
        }

        // 从完整URL中提取OSS key（存储路径）
        String pictureKey = extractOssKeyFromUrl(originUrl);
        // 清理原图
        ossManager.delete(pictureKey);

        // 清理压缩图
        if (StrUtil.isNotBlank(compressUrl)) {
            String compressKey = extractOssKeyFromUrl(compressUrl);
            ossManager.delete(compressKey);
        }

        // 清理缩略图
        if (StrUtil.isNotBlank(thumbnailUrl)) {
            String thumbnailKey = extractOssKeyFromUrl(thumbnailUrl);
            ossManager.delete(thumbnailKey);
        }
    }

    /**
     * 从完整URL中提取OSS key（存储路径）
     *
     * @param url 完整的图片URL
     * @return OSS存储key
     */
    private String extractOssKeyFromUrl(String url) {
        if (StrUtil.isBlank(url)) {
            return null;
        }
        // 方式1: 通过endpoint和bucketName提取key
        String endpoint = ossManager.getEndpoint();
        String bucketName = ossManager.getBucketName();

        // 构造匹配模式: https://{bucketName}.{endpoint}/
        String prefixPattern = String.format("https://%s.%s/", bucketName, endpoint);
        if (url.startsWith(prefixPattern)) {
            return url.substring(prefixPattern.length());
        }
        // 如果没有协议前缀，直接返回原URL
        return url;
    }

    /**
     * 根据图片URL从OSS获取图片主色调并更新到数据库
     * @param picture 图片对象
     * @return 是否更新成功
     */
    public boolean updatePictureColor(Picture picture) {
        try {
            // 从图片URL中提取OSS key（存储路径）
            String pictureKey = extractOssKeyFromUrl(picture.getOriginUrl());
            if (StrUtil.isBlank(pictureKey)) {
                log.warn("无法提取图片OSS key，图片ID: {}", picture.getId());
                return false;
            }

            // 从OSS获取图片主色调
            JSONObject colorInfo = ossManager.getColorInfoPictureJson(pictureKey);
            if (colorInfo != null && colorInfo.containsKey("RGB")) {
                String picColor = colorInfo.getStr("RGB");
                if (StrUtil.isNotBlank(picColor)) {
                    // 更新数据库中的主色调值
                    Picture updatePicture = new Picture();
                    updatePicture.setId(picture.getId());
                    updatePicture.setPicColor(picColor);
                    return this.updateById(updatePicture);
                }
            }
        } catch (Exception e) {
            log.error("更新图片主色调失败，图片ID: {}", picture.getId(), e);
        }
        return false;
    }

    /**
     * 批量更新所有没有主色调值的图片
     * @return 成功更新的数量
     */
    public int batchUpdatePicturesColor() {
        // 查询所有没有主色调值的图片
        List<Picture> pictures = this.lambdaQuery()
                .isNull(Picture::getPicColor)
                .or()
                .eq(Picture::getPicColor, "")
                .list();

        int successCount = 0;
        for (Picture picture : pictures) {
            if (updatePictureColor(picture)) {
                successCount++;
            }

            // 添加延迟以避免对OSS服务造成过大压力
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                break;
            }
        }

        return successCount;
    }

    @Override
    public Picture convertTagsFormat(Picture picture) {
        if (picture != null && StringUtils.isNotBlank(picture.getTags())) {
            // 使用JSONUtil将tags字符串转换为List<String>
            List<String> tagsList = JSONUtil.toList(picture.getTags(), String.class);
            // 将List<String>重新序列化为JSON字符串格式
            picture.setTags(JSONUtil.toJsonStr(tagsList));
        }
        return picture;
    }

    /**
     * 对前缀名称进行加工处理
     * @param prefix 原始前缀
     * @return 加工后的前缀
     */
    private String processNamePrefix(String prefix) {
        if (StrUtil.isBlank(prefix)) {
            return prefix;
        }
        // 1. 去除首尾空格
        prefix = prefix.trim();
        // 2. 限制长度（例如最多50个字符）
        if (prefix.length() > 30) {
            prefix = prefix.substring(0, 30);
        }
        // 3. 去除特殊字符，只保留字母、数字、中文、下划线和连字符
        prefix = prefix.replaceAll("[^a-zA-Z0-9\u4e00-\u9fa5_-]", "");
        // 4. 将连续的下划线或连字符替换为单个
        prefix = prefix.replaceAll("[-_]{2,}", "_");
        // 5. 去除开头和结尾的下划线或连字符
        prefix = prefix.replaceAll("^[-_]+|[-_]+$", "");
        return prefix;
    }

    /**
     * nameRule 格式：图片{序号}
     *
     * @param pictureList
     * @param nameRule
     */
    private void fillPictureWithNameRule(List<Picture> pictureList, String nameRule) {
        if (CollUtil.isEmpty(pictureList) || StrUtil.isBlank(nameRule)) {
            return;
        }
        long count = 1;
        try {
            for (Picture picture : pictureList) {
                String pictureName = nameRule.replaceAll("\\{index}", String.valueOf(count++));
                picture.setName(pictureName);
            }
        } catch (Exception e) {
            log.error("名称解析错误", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "名称解析错误");
        }
    }

    /**
     * 创建文字生成图片任务
     * @param textToImageCreateRequest 文字生成图片请求参数
     * @param loginUser 登录用户
     * @return 返回的图片生成任务响应
     */
    @Override
    public TextToImageResponse createTextToImageTask(TextToImageCreateRequest textToImageCreateRequest, User loginUser) {
        // 校验参数
        ThrowUtils.throwIf(textToImageCreateRequest == null || loginUser == null, ErrorCode.PARAMS_ERROR);
        
        // 转换DTO为API请求对象
        TextToImageRequest request = new TextToImageRequest();
        request.setModel(textToImageCreateRequest.getModel());
        request.setInput(new TextToImageRequest.Input());
        request.getInput().setPrompt(textToImageCreateRequest.getPrompt());
        request.getInput().setNegativePrompt(textToImageCreateRequest.getNegativePrompt());
        request.setParameters(new TextToImageRequest.Parameters());
        request.getParameters().setSize(textToImageCreateRequest.getSize());
        request.getParameters().setN(textToImageCreateRequest.getN());
        request.getParameters().setPromptExtend(textToImageCreateRequest.getPromptExtend());
        request.getParameters().setWatermark(textToImageCreateRequest.getWatermark());
        request.getParameters().setSeed(textToImageCreateRequest.getSeed());

        log.info("创建文字生成图片任务，参数: {}", request);
        // 调用API创建任务
        return textToImageApi.createTextToImageTask(request);
    }
    
    /**
     * 查询文字生成图片任务状态
     * @param taskId 任务ID
     * @param loginUser 登录用户
     * @return 返回的图片生成任务结果
     */
    @Override
    public TextToImageResponse getTextToImageTask(String taskId, User loginUser) {
        log.info("查询文字生成图片任务状态，任务ID: {}", taskId);
        // 校验参数
        ThrowUtils.throwIf(StringUtils.isBlank(taskId) || loginUser == null, ErrorCode.PARAMS_ERROR);
        // 调用API查询任务状态
        return textToImageApi.getTextToImageTask(taskId);
    }
}